<template>
  <div>
    <div class="market-nav" :class="{ transparent: transparent }">
      <!-- <button @click="test">test</button>
      <button @click="pru">pru</button> -->
      <div class="logo" @click="$router.push('/')"></div>
      <div class="nav-wrap font-size-18">
        <div class="nav-item" :class="{ active: path == '/preMarket' }">
          <RouterLink to='' @click="gotoApp">Airdrop Market</RouterLink>
        </div>
        <div class="nav-item" :class="{ active: path == '/pointsMarket' }">
          <RouterLink to="">Docs</RouterLink>
        </div>
        <div class="nav-item" :class="{ active: path == '/dashboard' }">
          <!-- <RouterLink to="">Spark Incentives</RouterLink> -->
		  <RouterLink to="">Coming Soon</RouterLink>
        </div>
        <!-- <div class="nav-item" :class="{ active: path == '/createOffer' }">
          <RouterLink to="/createOffer">Create offer</RouterLink>
        </div> -->
      </div>
      <div class="action-wrap font-size-18">
        <div class="connect-button font-size-16" @click="gotoApp">
          Go To Dapp
        </div>
      </div>
      <template v-if="false">
        <div class="action-wrap font-size-18">
          <!-- <RouterLink to="/createOffer"> -->
          <div class="create-button font-size-16" @click="ToCreateOffer">
            Create offer
          </div>
          <!-- </RouterLink> -->
          <a-dropdown trigger="click">
            <template #overlay>
              <a-menu>
                <a-menu-item
                  v-for="item in networkStore.networkList"
                  :key="item.id"
                  @click="handleMenuClick(item)"
                >
                  <div>
                    <div
                      class="token-icon"
                      :style="`background-image:url(${item.imgUrl});width:0.18rem;height:0.18rem;background-size:cover;display:inline-block;`"
                    ></div>
                    {{ item.networkName }}
                  </div>
                </a-menu-item>
              </a-menu>
            </template>
            <div class="chain-button">
              <div
                class="left-icon"
                :style="`background-image:url(${chain.imgUrl})`"
              ></div>
              <div class="current-chain">{{ chain.networkName }}</div>
              <div class="right-icon"></div>
            </div>
          </a-dropdown>
          <div class="connect-button font-size-16" @click="connectChain">
            {{ isConnected ? address : "Connect Wallet" }}
          </div>
        </div>
      </template>
    </div>
    <a-modal
      v-model:open="openAccount"
      :footer="null"
      class="account-modal"
      width="400px"
      style="padding: 0"
    >
      <div class="account-modal-content">
        <div class="account-address">
          {{ renderAddress }}
          <div class="copy-icon" @click="copyAddress"></div>
        </div>
        <div class="balance-cell">
          {{ `${renderBalance} ${walletAccount?.balance.symbol}` }}
        </div>
        <div class="cell" @click="handleDisconnect">
          <div class="label">
            <div class="icon"></div>
            Disconnect
          </div>
        </div>
      </div>
    </a-modal>
    <CreateOfferDialogVue
      v-if="createOfferVisible"
      :isOpen="createOfferVisible"
      @successCallback="handleCallback"
      @update:isOpen="handleModalClose"
    />
  </div>
</template>

<script>
import { useAccount } from "use-wagmi";
import { useWeb3Modal } from "@web3modal/wagmi/vue";
import {
  getAccount,
  signMessage,
  disconnect,
  fetchBalance,
  fetchToken,
  getNetwork as getNetworkByWallet,
  connect,
  fetchEnsName,
  fetchEnsAvatar,
  switchNetwork,
} from "@wagmi/core";
import {
  login,
  getNetwork,
  getAllToken,
  createOffer,
  heartbeat,
} from "@/api/market";
import { useTokenStore } from "@/stores/token";
import { useNetworkStore } from "@/stores/network";
import { mapStores } from "pinia";
import { optimism } from "@wagmi/core/chains";
import { InjectedConnector } from "@wagmi/core/connectors/injected";
import { message } from "ant-design-vue";
import CreateOfferDialogVue from "@/views/CreateOfferDialog.vue";
// const { address: watchAddress } = useAccount()
export default {
  components: {
    CreateOfferDialogVue,
  },
  data() {
    return {
      createOfferVisible: false,
      transparent: true, // 控制背景颜色
      path: "",
      address: null,
      isConnected: null,
      networkListParams: {
        pageNum: 1,
        pageSize: 10,
      },
      chain: {},
      setIntervalId: null,
      walletAccount: undefined,
      openAccount: false,
    };
  },
  computed: {
    // 注意，我们不是在传递一个数组，而是一个接一个的 store。
    // id+Store使用
    ...mapStores(useTokenStore, useNetworkStore),
    renderAddress() {
      if (this.walletAccount?.address) {
        const str = this.walletAccount.address;
        return `${str.substring(0, 4)}......${str.substring(str.length - 6)}`;
      }
      return "";
    },
    renderBalance() {
      if (this.walletAccount) {
        const formattedNumber = Number(
          this.walletAccount.balance.formatted
        ).toFixed(3);

        return formattedNumber.replace(/\.?0+$/, "");
      } else {
        return "0.000";
      }
    },
  },
  watch: {
    isConnected: {
      async handler(newVal, oldVal) {
        // console.log("wallet isConnected", newVal);
        // console.log(this.address);
        this.networkStore.isConnected = newVal;

        if (newVal) {
          this.handleLogin();
          const account = getAccount();
          const balance = await fetchBalance({
            address: account.address,
          });
          // const ensName = await fetchEnsName({
          //   address: account.address,
          // });
          this.walletAccount = { ...account, balance };
          this.networkStore.walletAccount = this.walletAccount;
        }
        if (!newVal) {
          this.networkStore.chain = {};
          this.walletAccount = undefined;
          this.networkStore.walletAccount = undefined;
          localStorage.removeItem("access_token");
          this.$router.push({
            path: "/",
          });
        }
      },
      immediate: false,
    },
    $route(to, from) {
      // 当路由发生变化时，会执行这里的代码
      // console.log('路由变更:', from.path, '->', to.path);
      // 根据路由变化执行相应的操作
      this.path = to.path;
      console.log(this.path);
      if (this.path == "/createOfferStep" && this.setIntervalId) {
        clearInterval(this.setIntervalId);
        this.setIntervalId = null;
      }
      if (this.path != "/createOfferStep" && this.isConnected) {
        this.loop();
      }
    },
    address(newVal, oldVal) {
      if (newVal !== oldVal && newVal && oldVal) {
        console.log("changeWalletAddress");
        this.handleDisconnect();
      }
    },
  },
  mounted() {
    const { address, isConnected } = useAccount();
    this.address = address;
    this.isConnected = isConnected;
    this.networkStore.isConnected = isConnected;
    this.getNetwork();
    this.getAllToken();
    this.loopCheckCreateOffer();
    this.loopHeartBeat();
    window.addEventListener("scroll", this.handleScroll); // 监听滚动条
  },
  unmounted() {
    clearInterval(this.setIntervalId);
  },
  methods: {
    gotoApp () {
      window.open('https://app.premius.market')
    },
    handleScroll() {
      // 获取滚动条位置、视口高度和整个文档的高度
      const scrollTop = window.scrollY;
      const windowHeight = window.innerHeight;
      const documentHeight = document.documentElement.scrollHeight;
      if (scrollTop > 50) {
        this.transparent = false;
      } else {
        this.transparent = true;
      }
    },
    connectChain() {
      const { open, close } = useWeb3Modal();

      if (!this.isConnected || !this.address) {
        open({ view: "Networks" });
      } else {
        // open({ view: "Account" });
        console.log(this.walletAccount);
        this.openAccount = true;

        // console.log("getChains", getNetworkByWallet());
      }
    },
    handleLogin() {
      signMessage({
        message: "Welcome to Premius!",
      })
        .then((signature) => {
          console.log("sign");
          // console.log(signature);
          login(this.address, signature)
            .then((res) => {
              console.log("res", res);
              const access_token = res.data.access_token;
              localStorage.setItem("access_token", access_token);

              // console.log('account',account);
              setTimeout(() => {
                location.reload();
              }, 500);
            })
            .catch((err) => {
              this.handleDisconnect();
            });
        })
        .catch((err) => {
          console.log("err", err);
          if (err.code == 4001) {
            this.handleDisconnect();
          }
        });
    },
    handleDisconnect() {
      disconnect();
      this.openAccount = false;
    },
    getNetwork() {
      getNetwork(this.networkListParams).then((res) => {
        this.networkStore.networkList = res.data;
        const { chain } = getNetworkByWallet();
        this.chain =
          res.data.filter((item) => item.networkId == chain?.id)[0] ||
          res.data[0];
        this.networkStore.chain = this.chain;
      });
    },
    getAllToken() {
      getAllToken({ tokenArea: 1 }).then((res) => {
        this.tokenStore.tokenList = res.data;
      });
      getAllToken({ tokenArea: 2 }).then((res) => {
        this.tokenStore.toeknList_point = res.data;
      });
    },
    async handleMenuClick(value) {
      if (!this.isConnected) {
        const { open, close } = useWeb3Modal();
        open({ view: "Networks" });
        return;
      } else {
        console.log("chainitem", value);
        // await disconnect();

        const result = await switchNetwork({
          chainId: Number(value.networkId),
        });
        this.chain = value;
        this.networkStore.chain = value;
        const account = getAccount();
        fetchBalance({
          address: account.address,
          chainId: Number(value.networkId),
        }).then((balance) => {
          console.log("balance", balance);
          this.walletAccount.balance = balance;
          this.networkStore.walletAccount = this.walletAccount;
        });
        console.log("resultaa", result);
      }
    },
    /** 轮询检查localStorage的createOffer有没有 */
    loopCheckCreateOffer() {
      // const currentPath = this.$route.path;
      // console.log('currentPath',currentPath)
      const createOfferFormString = localStorage.getItem("createOffer_form");
      if (!createOfferFormString) return;
      const submitForm = JSON.parse(createOfferFormString);
      createOffer(submitForm).then((res) => {
        if (res.code == 200) {
          localStorage.removeItem("createOffer_form");
        }
      });
    },
    loop() {
      // setTimeout(() => {
      //   this.loopCheckCreateOffer();
      // }, 1000);
      // this.setIntervalId = setInterval(() => {
      //   this.loopCheckCreateOffer();
      // }, 10000);
    },
    loopHeartBeat() {
      setInterval(() => {
        if (this.isConnected) {
          heartbeat().then((res) => {});
        }
      }, 60000);
    },
    async copyAddress() {
      await navigator.clipboard.writeText(this.walletAccount.address);
      message.success("Copy Address success");
    },
    handleCallback() {
      // this.offerDetailVisible = false;
      // this.createOfferVisible = false;
      // this.params.pageNum = 1;
      // this.offerList = [];
      // this.getList();
      setTimeout(() => {
        location.reload();
      }, 1000);
    },
    ToCreateOffer() {
      if (!this.networkStore.isConnected) {
        this.connectChain();
        return;
      }
      this.createOfferVisible = true;
    },
    handleModalClose(newVal) {
      this.createOfferVisible = newVal;
    },
  },
};
</script>

<style lang='scss' scoped>
@import "@/styles/base.scss";

.market-nav {
  padding: 0.18rem 0.57rem;
  background-color: #1f2023;
  // box-shadow: 0px 0.02rem 0.11rem#d8d5d5;
  border-block: 1px solid #3b3f4c;
  display: flex;
  align-items: center;
  position: fixed;
  top: 0;
  width: 100vw;
  height: 1rem;
  z-index: 9;
  transition: background-color 0.8s ease;
  &.transparent {
    background-color: transparent;
  }
  .logo {
    width: 2rem;
    height: 0.4rem;
    background-image: url("@/assets/images/logo_icon.png");
    margin-right: 1.07rem;
    background-size: cover;
    cursor: pointer;
  }
  .nav-wrap {
    display: flex;
    font-weight: bold;
    color: #a1a4aa;
    flex-grow: 1;
    .nav-item {
      margin-right: 1.18rem;
      &:hover {
        cursor: pointer;
        color: #fff;
      }
      &.active {
        color: #fff;
        position: relative;
      }
    }
  }
  .action-wrap {
    // margin-left: 2.39rem;
    display: flex;
    .chain-button {
      width: 2.05rem;
      height: 0.56rem;
      border-radius: $border-radius;
      text-align: center;
      line-height: 0.56rem;
      font-weight: 500;
      color: #fff;
      padding: 0 0.1rem;
      border: 1px solid #fff;
      margin-right: 0.23rem;
      padding: 0 0.1rem;
      &:hover {
        cursor: pointer;
      }
      display: flex;
      align-items: center;
      padding: 0 0.1rem;
      .left-icon {
        width: 0.18rem;
        height: 0.18rem;
        background-size: cover;
        background-image: url("@/assets/images/ch_icon.png");
        margin-right: 0.06rem;
        flex-shrink: 0;
      }
      .current-chain {
        flex-grow: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .right-icon {
        flex-shrink: 0;
        width: 0.18rem;
        height: 0.18rem;
        background-size: cover;
        background-image: url("@/assets/images/down_icon.png");
      }
    }
    .connect-button {
      width: 2.05rem;
      height: 0.56rem;
      border-radius: $border-radius;
      background: $primaryColor;
      text-align: center;
      line-height: 0.56rem;
      font-weight: 500;
      color: #fff;
      overflow: hidden; /* 确保内容超出容器宽度时隐藏 */
      white-space: nowrap; /* 保持文本在一行内显示，不换行 */
      text-overflow: ellipsis; /* 超出部分显示省略号 */
      padding: 0 0.1rem;
      &:hover {
        cursor: pointer;
        opacity: 1;
      }
    }
    .create-button {
      width: 2.05rem;
      height: 0.56rem;
      border-radius: $border-radius;
      text-align: center;
      line-height: 0.56rem;
      font-weight: 500;
      color: #fff;
      padding: 0 0.1rem;
      border: 1px solid #fff;
      margin-right: 0.23rem;
      padding: 0 0.1rem;
      &:hover {
        cursor: pointer;
        opacity: 1;
      }
    }
  }
}
</style>
<style lang="scss">
.account-modal-content {
  padding-top: 0.24rem;
  .account-address {
    font-size: 0.24rem;
    text-align: center;
    font-weight: 500;
    .copy-icon {
      display: inline-block;
      margin-left: 0.11rem;
      width: 0.2rem;
      height: 0.2rem;
      background-size: cover;
      background-image: url("@/assets/images/copy.png");
      cursor: pointer;
    }
  }
  .balance-cell {
    margin: 0.11rem 0;
    font-size: 0.16rem;
    text-align: center;
  }
  .cell {
    display: flex;
    align-items: center;
    .label {
      font-size: 0.2rem;
      font-weight: 500;
      color: #999999;
      padding: 0.05rem 0.1rem;
      display: flex;
      align-items: center;
      .icon {
        margin-right: 0.11rem;
        width: 0.24rem;
        height: 0.24rem;
        background-size: cover;
        background-image: url("@/assets/images/disconnect.png");
      }
    }
    cursor: pointer;
    opacity: 0.5;
    background: #fdfdfd;
    border-radius: 0.05rem;
    &:hover {
      opacity: 1;
    }
  }
}
</style>